package com.cicadamob.contact.api.Utils.Data.File;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Environment;

public class FileUtil {
	/**
	 * 写log到文件
	 * 
	 * @param context
	 * @param folderDir
	 *            log目录
	 * @param fileName
	 *            log文件名称
	 * @param logMessage
	 *            log内容
	 * @param logPerDay
	 *            是否每日一个log文件
	 */
   public static void writeLogToFile(String folderDir, String fileName, String logMessage, boolean logPerDay){
	    if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
	    	return;
	    }
		try {
			File rootFolder = new File(folderDir);
			if (!rootFolder.exists()) {
				rootFolder.mkdirs();
			}
			File logFile = null;
			if (logPerDay) {
				String data = new SimpleDateFormat("yyyyMMdd")
						.format(new Date(System.currentTimeMillis()));
			//	logFile = new File(folderDir + "/" + fileName + data
			//			+ File.separator + "txt");
				logFile = new File(folderDir + "/" + fileName + data
						+ "." + "txt");
			} else {
				//logFile = new File(folderDir + "/" + fileName
			//			+ File.separator + "txt");
				logFile = new File(folderDir + "/" + fileName
						+ "." + "txt");
			}
			if (!logFile.exists()) {
				logFile.createNewFile();
			}
			// 每次写入时，都换行写
			String strContent = "\r********************************************************\n\r"
					+ new SimpleDateFormat("yyyyMMdd").format(new Date())
					+ ":" + logMessage + "\n";
			RandomAccessFile raf = new RandomAccessFile(logFile, "rw");
			raf.seek(logFile.length());
			raf.write(strContent.getBytes());
			raf.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
   }
}
